/*

    Real-Time Systems Simulator v2 si an event based real-time systems
simulator
    Copyright (C) <2010>  Damien Masson -- visit <http://dajam.fr/>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>

 */
package yartiss.engine.simulation.system.taskset;

import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import yartiss.engine.simulation.system.ITask;
import yartiss.engine.simulation.system.ITaskSet;

/**
 * This class model a periodic task set with both time and energy requirement A
 * unique task per priority is allowed
 * 
 * @author Damien Masson
 * 
 */
public class PriorityTaskSet implements ITaskSet {

	private final TreeSet<ITask> tasks;
	private int id;

	private static final Comparator<ITask> comparator = new Comparator<ITask>() {
		@Override
		public int compare(ITask t1, ITask t2) {
			return (int) (t1.getPriority() - t2.getPriority());
		}
	};

	public PriorityTaskSet() {
		this.tasks = new TreeSet<ITask>(comparator);
	}

	@Override
	public boolean addTask(ITask t) {
		return tasks.add(t);
	}
	@Override
	public boolean addTasks(List<ITask> t) {
		return tasks.addAll(t);
	}
	@Override
	public SortedSet<ITask> getActiveTasks(long date) {
		SortedSet<ITask> activeTasks = new TreeSet<ITask>(comparator);
		for (ITask t : tasks)
			if (t.isActive())
				activeTasks.add(t);
		return activeTasks;
	}

	@Override
	public Iterator<ITask> iterator() {
		return tasks.iterator();
	}

	@Override
	public int getAllTasksCount() {
		return tasks.size();
	}

	@Override
	public SortedSet<ITask> getHeadSet(ITask task, boolean inclusive) {
		return tasks.headSet(task, inclusive);
	}

	@Override
	public int getId() {
		return id;
	}

	@Override
	public int setId(int id) {
		return this.id = id;
	}

	@Override
	public ITask getOne() {
		return tasks.first();
	}

	@Override
	public ITaskSet cloneTaskSet() {
		PriorityTaskSet set = new PriorityTaskSet();
		for (ITask task : tasks) {
			set.addTask(task.cloneTask());
		}
		return set;
	}

}
